/*
 * @Author: fisher
 * @Date: 2023-07-06 17:51:05
 * @LastEditTime: 2024-01-02 14:57:58
 * @LastEditors: lbz_dev 1982212843@qq.com
 * @Description:
 * @FilePath: \front-end-template\src\modules\Digital\utils\cesiumDraw\polygon.js
 */
import { screen2degrees, GenerateId } from "./utils.js";
/* eslint-disable */
export default (handler, collection, features, currentAction, options) => {
  const color = options.color || "#e74c3c";
  const opacity = options.opacity || 1;
  const elevation = options.elevation || 1;
  const outline_width = 5;
  const outline_color = "#34495e";
  let points = [];
  let tempPoint = [];
  let coordinates = [];
  let tempPolygon = undefined;
  let _primitives;
  const leftClickCb = (e) => {
    const point = screen2degrees(e.position);
    console.log('点击坐标',point);
    points.push(point.x, point.y);
    coordinates.push([point.x, point.y]);
    if (!_primitives) {
      _primitives = new Cesium.PrimitiveCollection();
      scene.primitives.add(_primitives);
    }
 
    // 当有第一个点后开启移动
    if (points.length == 2) {
      handler.setInputAction(
        mouseMoveCb,
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
      );
      // if (!tempPolygon) {
      //   draw_dynamic();
      // }
    }
  };
  const mouseMoveCb = (e) => {
    tempPoint = screen2degrees(e.endPosition);
    // if (points.length >= 4) {
    //   points.length = points.length - 2;
    // }
   if(points.length!=2) points.splice(-2);
    points.push(tempPoint.x, tempPoint.y);
    draw_dynamic();
  };
  const rightClickCb = (e) => {
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // 取消最后一个未选择点位坐标tempPoint
    points.length = points.length - 2;
    // polygon坐标点封闭,需要首位坐标一致
    coordinates.push([coordinates[0][0], coordinates[0][1]]);
    // 处理coordinates的数组层级
    coordinates = [coordinates];
    // 绘制结果
    draw_polygon();
    // 重置动态线，以及静态线初始值
    collection.entities.remove(tempPolygon);
    tempPolygon = undefined;
    tempPoint = [];
    points = [];
    coordinates = [];
  };
  //绘制动态线
  const draw_dynamic = () => {
    // tempPolygon = collection.entities.add({
    //   name: 'tempPolygon',
    //   polygon: {
    //     // 这个方法上面有重点说明
    //     hierarchy:{
    //       positions: new Cesium.Cartesian3.fromDegreesArray(points)
    //     },
    //     // 边框
    //     // outline: true,
    //     // outlineColor: Cesium.Color.fromCssColorString(outline_color),
    //     // outlineWidth: outline_width,
    //     height: elevation,
    //     // 填充的颜色
    //     material: Cesium.Color.fromCssColorString(color).withAlpha(opacity),
    //   }
    // });
    //传入顶点坐标
    _primitives.removeAll()
    var polygon = new Cesium.PolygonGeometry({
      polygonHierarchy: new Cesium.PolygonHierarchy(
        Cesium.Cartesian3.fromDegreesArray(points)
      ),
    });
    //相关属性
    let options = {
      allowPicking: true,
      releaseGeometryInstances: false, //保留顶点
      geometryInstances: new Cesium.GeometryInstance({
        geometry: polygon,
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.ORANGE
          ),
        },
      }),
      appearance: new Cesium.PerInstanceColorAppearance({
        translucent: false,
        closed: true,
      }),

      asynchronous: false,
    };
    let primitive = new Cesium.Primitive(options);
    //自定义一个原始参照旋转度
    primitive.rotation = { x: 0, y: 0, z: 0 };
    _primitives.add(primitive);
  };

  //绘制结果线
  const draw_polygon = () => {
    const id = GenerateId(13);
    if (points.length > 4) {
      _primitives.removeAll()
      var polygon = new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(
          Cesium.Cartesian3.fromDegreesArray(points)
        ),
      });
      //相关属性
      let options = {
        allowPicking: true,
        releaseGeometryInstances: false, //保留顶点
        geometryInstances: new Cesium.GeometryInstance({
          geometry: polygon,
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.ORANGE
            ),
          },
        }),
        appearance: new Cesium.PerInstanceColorAppearance({
          translucent: false,
          closed: true,
        }),
  
        asynchronous: false,
      };
      let primitive = new Cesium.GroundPrimitive(options);
      const yellowEdge = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
      yellowEdge.uniforms.color = Cesium.Color.YELLOW;
      yellowEdge.uniforms.length = 2.9;
      yellowEdge.selected = [primitive];
      viewer.scene.postProcessStages.add(Cesium.PostProcessStageLibrary.createSilhouetteStage([yellowEdge]));
      console.log("yellowEdge",yellowEdge);
      collection.entities.add({
        id: id,
        name: "staticPolygon",
        polygon: {
          // Cesium.Cartesian3.fromDegreesArray([经度1, 纬度1, 经度2, 纬度2,])
          // Cesium.Cartesian3.fromDegreesArrayHeights([经度1, 纬度1, 高度1, 经度2, 纬度2, 高度2])
          hierarchy: {
            positions: new Cesium.Cartesian3.fromDegreesArray(points),
          },
          height: elevation,
          // // 边框
          // outline: true,
          // outlineColor: Cesium.Color.fromCssColorString(outline_color),
          // outlineWidth: outline_width,
          // 线的颜色
          material: Cesium.Color.fromCssColorString(color).withAlpha(opacity),
        },
      });
      // 新增feature数据
      const feature = {
        type: "Feature",
        properties: {
          type: "polygon",
          id: id,
          outline_color: outline_color,
          outline_width: outline_width,
          color: color,
          opacity: opacity,
          elevation: elevation,
        },
        geometry: {
          type: "Polygon",
          coordinates: coordinates,
        },
      };
      features.push(feature);
      // currentAction && currentAction(feature)
    } else {
      return;
    }
  };
  handler.setInputAction(leftClickCb, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  handler.setInputAction(rightClickCb, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};
